/**
 * @file main.js
 * @brief 云存储系统前端交互脚本
 */

// 拖拽上传功能
const uploadArea = document.querySelector('.upload-area');
const fileInput = document.getElementById('fileInput');

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, preventDefaults, false);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

['dragenter', 'dragover'].forEach(eventName => {
    uploadArea.addEventListener(eventName, highlight, false);
});

['dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, unhighlight, false);
});

function highlight(e) {
    uploadArea.classList.add('dragover');
}

function unhighlight(e) {
    uploadArea.classList.remove('dragover');
}

uploadArea.addEventListener('drop', handleDrop, false);

function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    
    if (files.length > 0) {
        fileInput.files = files;
        uploadFile();
    }
}

/**
 * @brief 文件上传函数
 */
function uploadFile() {
    const file = fileInput.files[0];
    if (!file) {
        showResult('uploadResult', '请选择要上传的文件', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    const progressBar = document.getElementById('progressBar');
    const progress = document.getElementById('uploadProgress');
    const result = document.getElementById('uploadResult');

    // 显示进度条
    progress.style.display = 'block';
    result.style.display = 'none';

    const xhr = new XMLHttpRequest();

    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressBar.style.width = percentComplete + '%';
        }
    });

    xhr.addEventListener('load', function() {
        progress.style.display = 'none';
        
        if (xhr.status === 200) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    let message = `文件上传成功！<br>`;
                    message += `<div class="file-info">`;
                    message += `<div><strong>文件ID:</strong> <span style="font-family: monospace; font-size: 1.2em; color: #4facfe;">${response.file_id}</span></div>`;
                    message += `<div><strong>文件名:</strong> ${response.filename}</div>`;
                    message += `<div><strong>文件大小:</strong> ${formatFileSize(response.filesize)}</div>`;
                    if (response.is_duplicate) {
                        message += `<div><strong>状态:</strong> <span style="color: #ffc107;">重复文件，返回已有ID</span></div>`;
                    } else {
                        message += `<div><strong>状态:</strong> <span style="color: #28a745;">新文件上传成功</span></div>`;
                    }
                    message += `</div>`;
                    
                    showResult('uploadResult', message, 'success');
                } else {
                    showResult('uploadResult', '上传失败: ' + response.error, 'error');
                }
            } catch (e) {
                showResult('uploadResult', '服务器响应解析失败', 'error');
            }
        } else {
            showResult('uploadResult', '上传失败，服务器错误', 'error');
        }
    });

    xhr.addEventListener('error', function() {
        progress.style.display = 'none';
        showResult('uploadResult', '网络错误，上传失败', 'error');
    });

    xhr.open('POST', '/upload', true);
    xhr.send(formData);
}

/**
 * @brief 文件下载函数
 */
function downloadFile() {
    const fileId = document.getElementById('fileId').value.trim();
    
    if (!fileId) {
        showResult('downloadResult', '请输入文件ID', 'error');
        return;
    }

    if (fileId.length !== 6) {
        showResult('downloadResult', '文件ID必须是6位字符', 'error');
        return;
    }

    // 直接跳转到下载链接
    window.open('/download/' + fileId, '_blank');
    showResult('downloadResult', '下载链接已打开，如果没有自动下载请检查浏览器设置', 'success');
}

/**
 * @brief 获取文件信息函数
 */
function getFileInfo() {
    const fileId = document.getElementById('fileId').value.trim();
    
    if (!fileId) {
        showResult('downloadResult', '请输入文件ID', 'error');
        return;
    }

    if (fileId.length !== 6) {
        showResult('downloadResult', '文件ID必须是6位字符', 'error');
        return;
    }

    fetch('/info/' + fileId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let message = `文件信息查询成功！<br>`;
                message += `<div class="file-info">`;
                message += `<div><strong>文件ID:</strong> <span style="font-family: monospace; font-size: 1.1em;">${data.file_id}</span></div>`;
                message += `<div><strong>文件名:</strong> ${data.filename}</div>`;
                message += `<div><strong>文件大小:</strong> ${formatFileSize(data.filesize)}</div>`;
                message += `<div><strong>MIME类型:</strong> ${data.mime_type}</div>`;
                message += `<div><strong>上传时间:</strong> ${data.upload_time}</div>`;
                message += `<div><strong>下载次数:</strong> ${data.download_count}</div>`;
                message += `</div>`;
                
                showResult('downloadResult', message, 'success');
            } else {
                showResult('downloadResult', '查询失败: ' + data.error, 'error');
            }
        })
        .catch(error => {
            showResult('downloadResult', '网络错误: ' + error.message, 'error');
        });
}

/**
 * @brief 显示结果函数
 * @param {string} elementId 元素ID
 * @param {string} message 消息内容
 * @param {string} type 消息类型
 */
function showResult(elementId, message, type) {
    const result = document.getElementById(elementId);
    result.innerHTML = message;
    result.className = 'result ' + type;
    result.style.display = 'block';
}

/**
 * @brief 格式化文件大小
 * @param {number} bytes 文件大小（字节）
 * @return {string} 格式化后的文件大小
 */
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 文件ID输入框回车事件
document.getElementById('fileId').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        downloadFile();
    }
}); 